<template>
  <div class="app-container">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="">
        <el-select v-model="searchMap.where.quType" placeholder="请选择">
          <el-option
            v-for="item in typeArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="">
        <el-input
          v-model="searchMap.where.content"
          placeholder="题目内容"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="searchMap.where.repoIds"
          multiple
          placeholder="请选择"
        >
          <el-option
            v-for="item in repoList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search()">查询</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="toQuAdd()"
          >添加</el-button
        >
        <el-button type="danger" icon="el-icon-delete" @click="delBatch()"
          >批量删除</el-button
        >
        <el-button type="danger" icon="el-icon-delete" @click="exportQu()"
          >导出</el-button
        >
      </el-form-item>

      <el-form-item label="导入试题">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          :on-remove="handleRemove"
          name="file"
          :limit="1"
          :on-success="uploadSuccess"
          :auto-upload="true"
          list-type="picture"
        >
          <el-button size="small" type="primary" @click="uploadXlsxData()"
            >点击上传</el-button
          >
          <div slot="tip" class="el-upload__tip">
            <input
              type="file"
              ref="upload"
              @change="readExcel"
              accept=".xls, .xlsx"
            />
            只能上传xls/xlsx文件
          </div>
        </el-upload>
      </el-form-item>
    </el-form>

    <el-table
      :data="quList"
      stripe
      style="width: 100%"
      ref="repotable"
      @select="selectItem"
      @select-all="selectItem"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="quType" label="题目类型" width="100">
        <template slot-scope="scope">
          <div>
            {{ scope.row.quType | quTypeFilter }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="quType" label="难易程度" width="100">
        <template slot-scope="scope">
          <div>
            {{ scope.row.level }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="题目内容" width="400">
        <template slot-scope="scope">
          <div>
            <!-- <a href="javascript:void(0)" @click.prevent="toUpdate(scope.row.id)">{{scope.row.content}}</a> -->

            <router-link
              :to="{ name: 'quupdate', params: { quId: scope.row.id } }"
              ><p v-html="scope.row.content"></p
            ></router-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column label="操作">
        <div slot-scope="scope">
          <el-button
            @click="del(scope.row.id)"
            size="small"
            type="danger"
            icon="el-icon-delete"
            circle
          ></el-button>
          <el-button
            @click="edit(scope.row.id)"
            size="small"
            type="primary"
            icon="el-icon-edit"
            circle
          ></el-button>
        </div>
      </el-table-column>
    </el-table>
    <br /><br />
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchMap.now"
      :page-sizes="[3, 5, 50, 100]"
      :page-size="searchMap.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>
<script>
import { list, deleteById, deleteByIds } from "@/api/qu";
import { findAll } from "@/api/repo";
import * as XLSX from "xlsx";
export default {
  data() {
    return {
      uploadUrl: `${process.env.VUE_APP_BASE_API}/excel/import`,
      headers: { token: localStorage.getItem("token") },
      repoList: [],
      searchMap: {
        now: 1,
        size: 5,
        where: {
          repoIds: [],
        },
      },
      quIds: [],
      quList: [],
      total: 0,
      dialogFormVisible: false,
      repoForm: {
        title: "",
        remark: "",
      },
      typeArr: [
        {
          value: 1,
          label: "单选题",
        },
        {
          value: 2,
          label: "多选题",
        },
        {
          value: 3,
          label: "判断题",
        },
      ],
      xlsxData: [],
    };
  },
  filters: {
    quTypeFilter(value) {
      const map = {
        1: "单选题",
        2: "多选题",
        3: "判断题",
        4: "简答题",
      };
      return map[value];
    },
  },
  methods: {
    readExcel(e) {
      const files = e.target.files;
      const fileReader = new FileReader();
      fileReader.readAsBinaryString(files[0]);
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary",
          }); // 二进制读取
          const wsname = workbook.SheetNames[0]; // 取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); // 生成json表格内容
          //TODO :后续需要补充表单上传解析
          console.log(ws);
          this.xlsxData = ws;
        } catch (e) {
          return false;
        }
      };
    },
    uploadXlsxData() {
      //TODO :将转化后的 json 上传到服务器
      
    },
    handleRemove(file, fileList) {},
    uploadSuccess(file, fileList) {},

    search() {
      list(this.searchMap).then((res) => {
        this.quList = res.list;
        this.total = res.total;
      });
    },

    findRepoList() {
      findAll().then((res) => {
        this.repoList = res;
      });
    },
    toQuAdd() {
      this.$router.push({ name: "quadd" });
    },

    handleSizeChange(size) {
      //pageSize 改变时会触发
      this.searchMap.size = size;
      this.search();
    },
    handleCurrentChange(page) {
      //currentPage 改变时会触发
      this.searchMap.now = page;
      this.search();
    },
    toUpdate(id) {
      this.$router.push({ name: "quupdate", params: { quId: id } });
    },

    exportQu() {
      exportQu().then((res) => {
        // 这里 data 就是后台响应的二进制数据流
        let blob = new Blob([res], {
          type: "application/octet-stream",
        });
        // 没有指定下载的名称 默认filename.xls
        let filename = "题目列表.xls";
        // 有 msSaveBlob  直接保存
        if (typeof window.navigator.msSaveBlob !== "undefined") {
          window.navigator.msSaveBlob(blob, filename);
        } else {
          // 没有
          // 创建 blobURL
          var blobURL = window.URL.createObjectURL(blob);
          // 创建 a 标签
          var tempLink = document.createElement("a");
          // 隐藏 a 标签
          tempLink.style.display = "none";
          // 设置 a 标签 href 连接
          tempLink.href = blobURL;
          // 设置 a 标签属性为 download (下载文件)
          tempLink.setAttribute("download", filename);
          if (typeof tempLink.download === "undefined") {
            tempLink.setAttribute("target", "_blank");
          }
          document.body.appendChild(tempLink);
          tempLink.click();
          document.body.removeChild(tempLink);
          window.URL.revokeObjectURL(blobURL);
        }
      });
    },
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteById(id).then((res) => {
            this.searchMap.now = 1;
            this.search();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    edit(id) {
      this.$router.push({ path: "/qu/add", query: { id: id } });
    },
    delBatch() {
      this.$confirm("此操作将永久删除选中的批量题目类型, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteByIds(this.quIds).then((res) => {
            this.searchMap.now = 1;
            this.search();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    selectItem(selection, row) {
      this.quIds = [];
      selection.forEach((item) => {
        this.quIds.push(item.id);
      });
    },
  },
  created() {
    //获取路由参数
    // console.log(this.$route.query.id);
    this.search();

    //查询题库列表
    this.findRepoList();
  },
};
</script>